const {Commodity} = require("../../../models/commodity")
const {Book} = require("../../../models/Books")
const stringRandom = require("string-random");

module.exports = async (req, res) => {
    //接收商品信息参数
const {Art_No,user_id,ISBN,customPrice,freight,
    appearance,deliveryLocation,firstCategory,secondCategory} = req.body
  try{
    if(Art_No == ""){
    //在商品集合中创建该商品信息
    createCommodity(user_id, ISBN, appearance, customPrice, freight, deliveryLocation);
    //更新图书分类信息
    Book.updateOne({ISBN:ISBN}, {$set:{"firstCategory":firstCategory}});
    Book.updateOne({ISBN:ISBN}, {$push:{"secondCategory":secondCategory}});
    res.send({errCode:"0",msg:"上传成功"})
    }else{
       const up = await Commodity.updateOne({Art_No:Art_No}, 
        {$set:{"firstCategory":firstCategory,"customPrice":customPrice,
        "freight":freight, "appearance":appearance,
        "deliveryLocation":deliveryLocation,"firstCategory":firstCategory,
        "secondCategory":secondCategory},});
       res.send({errCode:"0",msg:"修改成功"})
    }
    
    }catch(e){
        res.status(400).send({errCode:"1",msg:"请求错误"})
    }
}
    // 在商品集合中创建一条文档
    async function createCommodity(user_id, ISBN, appearance, customPrice, freight, deliveryLocation) {
        var Art_No = stringRandom(16, { numbers: true });
        var res = await Commodity.findOne({Art_No:Art_No},{Art_No:1});
        while(res !== null){
            Art_No = stringRandom(16, { numbers: true });
            res = await Commodity.findOne({Art_No:Art_No},{Art_No:1});
        }
        const commodity = await Commodity.create({
            //商品编号唯一
            Art_No: Art_No,
            user_id: user_id,
            ISBN: ISBN,
            appearance: appearance,
            customPrice: customPrice,
            freight: freight,
            deliveryLocation: deliveryLocation,
            evaluation: [],
        });
        console.log("数据添加成功!");
    }